/**
 * Created by lixiaodi on 2018/10/10.
 */
var states = [{code: 1, text: '账号开启' }, {code: 2, text: '账号锁定'}];
mini.parse();
var roleLists = mini.getByName('role.roleId'); 		//得到角色列表
var passwordEl = mini.getByName('password');		//得到密码输入框
var okPasswordEl = mini.getByName('okPassword');	//得到重置密码输入框
var resetBtn = mini.get('resetBtn');				//按钮
var roleIdBtn = mini.get('roleId');					//角色选择框
var userNameInput = mini.get('userName');
var userCodeInput = mini.get('PersonnelFiles_code');
var useruName=mini.get("PersonnelFiles_name");
var PersonnelFiles_id=mini.get("PersonnelFiles_id");
var personCode = mini.get('uCode');
var grid = mini.get('datagrid1');

var data5;
var date;
var personnelId;
var personnelId1;
var showState = true;
var id1;
//页面初始化(账号只读：防止浏览器默认填充账号密码)


$(function(){
	document.getElementById('userName$text').setAttribute("readOnly",'true');
});
//初始化
$(function(){
    $.ajax({
        url: ajaxUrl + "/role/list.do",
        type: 'POST',
        contentType : "application/json",
        success: function (data) {
            console.log(data);

            var roleObj = data.data;
            grid.setData(roleObj);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //alert(jqXHR.responseText);
            //CloseWindow();
            console.log('请求失败');
        }
    })
});
//角色列表下拉框列表
//$(function(){
//    roleLists.setUrl(ajaxUrl + "/role/list.do");
//});
var form = new mini.Form("form1");  //得到页面上的表单
//角色选择
function changeRole(){
	//var btnEdit = this;
	mini.open({
        url: bootPATH + "../frame/frame1/pages/alertBox/roleChangeWin.html",
        title: "选择角色",
        width: 500,
        height: 360,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                console.log(data);
                var ids = [];
                var names = [];
                for (var i = 0, l = data.length; i < l; i++) {
                    var r = data[i];
                    ids.push(r.roleId);
                    names.push(r.roleName);
                }
                var id = ids.join(',');
                var nameStr = names.join(',');
                if (data) {
                	roleIdBtn.setValue(id);
                	roleIdBtn.setText(nameStr);
                }
            }
        }
    });
}
//人员参照
function changePerson(){
	//var btnEdit = this;
	mini.open({
        url: bootPATH + "../frame/frame1/pages/alertBox/personReferenceWin.html",
        title: "人员档案",
        width: 1200,
        height: 700,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                console.log(data);
                var personInfo = data;
                //得到form表单的值
                var formObj = form.getData();
                console.log(formObj);

                //赋值
                console.log("赋值");
                console.log(personInfo);
                console.log("人员id");
                console.log(personInfo.PersonnelFiles_id);
                 id1=personInfo.PersonnelFiles_id;
                formObj.user_phone = personInfo.PersonnelFiles_phone;
                formObj.user_email = personInfo.PersonnelFiles_Email;
                formObj.personCode=personInfo.PersonnelFiles_code;
                formObj.uName=personInfo.PersonnelFiles_name;


                // if(personInfo.company){
                // 	formObj.user_company = personInfo.company.companyName;
                // }
                // if(personInfo.company){
                // 	formObj.user_department = personInfo.department.departmentName;
                // }

                // personCode.setValue(personInfo.PersonnelFiles_OperatorCode);
                // personCode.setText(personInfo.PersonnelFiles_OperatorName);
                console.log(formObj,'用户信息');
                userCodeInput.setValue(formObj.personCode);
                userCodeInput.setText(formObj.personCode);
                useruName.setValue(formObj.uName);
                useruName.setText(formObj.uName);
            }
        }
    });
}
//密码确定校验
function onPasswordBlur(){
	var passwordTxt1 = passwordEl.getValue();
	var okPasswordElTxt2 = okPasswordEl.getValue();
	if(!(passwordTxt1 == okPasswordElTxt2)){
		mini.alert('确认密码和密码要一致');
	}
}
//保存
function SaveData() {
    var rows=grid.getSelecteds();
     roleId=[];
    console.log(rows);
    rows.forEach(function (items) {
        roleId.push(items.roleId)
    })
	//校验
    form.validate();
    if (form.isValid() == false) return;
  	//得到用户填写信息
    var ids = form.getData();
    console.log(ids);
    //编辑
    if(ids.userId){
    	ajaxSave(ids);
    //新增
    }else{
    	if(ids.password == ids.okPassword){
    		ajaxSave(ids);
	    }else{
	        mini.alert("密码两次输入不一致");
	    }
    }
   

}
//标准方法接口定义（编辑）
function SetData(data) {
    if (data.action == "edit") {
    	//密码/重置密码输入框禁用
    	//passwordEl.disable();
        //okPasswordEl.disable();
        userNameInput.disable();
        // findByUserName.disable();
    	$('#okPassword').hide();
    	$('#okText').hide();
        //跨页面传递的数据对象，克隆后才可以安全使用
        data = mini.clone(data);
        console.log(data);
        date=mini.clone(data.row);
        console.log(date);
        var userId = data.id;
        $.ajax({
            url: ajaxUrl + "/user/findByUserInfoId.do?userId=" + userId,
            success: function (data) {
            	console.log(data);
            	console.log(data.data.personnelId);
                id1=data.data.personnelId;
            	//赋值
                var o = mini.decode(data);
                console.log(o);
                // personnelId=o.data.personnelId;
                if(o.data.createDate){
                	o.data.createDate = formatDate(o.data.createDate);
                }
                o.data.createDate
                form.setData(o.data);
                userCodeInput.setValue(o.data.personCode);
                userCodeInput.setText(o.data.personCode);
                // if(o.roleIds){
                // 	roleIdBtn.setValue(o.roleIds);
                //   	//roleIdBtn.setText(o.data.role.roleName);
                //   	roleIdBtn.setText(o.roleNames);
                // }
                form.setChanged(false);
                $.ajax({
                    type 	: 'POST',
                    url  	: ajaxUrl + '/user/findrole.do',
                    data 	: {
                       userId:userId
                    },
                    success : function(data){
                      console.log(data);
                      data5=mini.clone(data);
                        console.log(data5);
                        var rowsArr=[];
                      // console.log(typeof data5[0].roleId);
                        data5.forEach(function (item) {
                            var row = grid.findRow(function (row) {
                                if(row.roleId == item.roleId)
                                    return true;
                            });
                            console.log(row);
                            rowsArr.push(row);
                        });
                        console.log(rowsArr);
                        grid.selects(rowsArr,true);
                    },
                    error   : function(message) {
                        alert("963")
                    }
                })
            },
            error:function(data){
                mini.alert('失败');
            }
        });
    }else if(data.action == "new"){
        //新增时，密码输入框启用
        passwordEl.enable();
        //重置密码输入框禁用
        okPasswordEl.enable();
        //新增时模块状态默认开启
        var userState = mini.getByName('userState');
        userState.setValue(states[0].code);
        userState.setText(states[0].text);
    }
}
//父页面传值
function GetData() {
    var o = form.getData();
    return o;
}

//当选择角色改变时
function onUserChanged(e) {
    var roleIdValue = roleLists.getValue();
}

//重置
function onReset(){
    var ids = form.getData();
    var userId = ids.userId;
    var resetBtn = mini.get("resetBtn");
    var passwords = mini.get("password");
    passwords.allowInput="false";
    $.ajax({
        url: ajaxUrl + "/user/replacePassword.do?userId=" + userId,
        type:"post",
        success: function (data) {
            resetBtn.enabled="true";
        }
    });

}
//密码可见
function seeFun(e){
	var pwInput = $('#password1')[0];
	console.log(pwInput);
	console.log(pwInput.class);
}
//校验账号名称是否重复
function findByUserName(){
	var ids = form.getData();
	var userName = ids.userName;
	
	$.ajax({
		type 	: 'POST',
		url  	: ajaxUrl + '/user/findUserName.do',
		data 	: {
			userName : userName
		},
		success : function(data){
		    console.log(data);
			if(data.state == 'error'){
				mini.alert(data.message);
				// mini.getByName('userName').setValue('');
			}
		},
		error   : function(message) {
			mini.alert(message);
		}
	})
}
//校验模块必输
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}
//保存时确认密码是否和密码一致
function onConfirmValidation(e){
	var passwordTxt1 = passwordEl.getValue();
	if (e.isValid) {
		if(e.value != passwordTxt1){
			e.errorText = '确认密码和密码要保持一致';
            e.isValid = false;
		}
    }
}
//关闭子页面
function CloseWindow(action) {
    if (action == "close" && form.isChanged()) {
        if (confirm("数据被修改了，是否先保存？")) {
            return false;
        }
    }
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}
function onOk(e) {
    SaveData();
}
function onCancel(e) {
    CloseWindow("cancel");
}
//保存ajax
function ajaxSave(ids){
    console.log(roleId);
	var userInfo = {
            userId : ids.userId,
            userCode: ids.userCode,
            userName : ids.userName,
            personCode : ids.personCode,
            uName : ids.uName,
            password: ids.password,
            roleId :roleId,
            userState : ids.userState,
            loginDate : ids.loginDate,
            createDate : ids.createDate,
            personnelId:id1,
        };
        console.log(userInfo,'保存');
        if(userInfo.loginDate=="-"){
            userInfo.loginDate=null
        }
        if(userInfo.createDate=="-"){
            userInfo.createDate=null
        }

    console.log(userInfo,'保存');
        userInfo = JSON.stringify(userInfo);
         console.log(userInfo,'保存');

        $.ajax({
            url: ajaxUrl + "/user/saveUser.do",
            type: 'POST',
            data: userInfo,
            contentType : "application/json",
            success: function (data) {
                CloseWindow("save");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //alert(jqXHR.responseText);
                CloseWindow();
            }
        });
}
